<template>
  <div class="page-main" style="height: calc(100vh - 125px)">
    <!-- 右侧内容区域 -->
    <query-page
      ref="queryForms"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      title="人员物料维护"
      height="calc(100vh - 200px)"
      :has-line="false"
      row-selection-type="checkbox"
      :split-no-left="false"
      :split-size="0.2"
      @selection-change="handleSelectionChange"
      @search="getData"
      @reset="getData"
      @page-change="pageChange"
      @page-size-change="pageSizeChange"
    >
      <template #split-left>
        <personTree @personalClick="personalClick"></personTree>
      </template>
      <template #container-side>
        <block v-permission="['base:user-material-config:import']">
          <batch-import
            file-code="infra_personnelAndMaterials"
            :import-url="`/api/procurement/infra/user-material-config/import`"
            export-type="apiUrl"
            title="人员物料维护"
            btn-tititle="Excel导入"
            :before-open="beforeOpen"
            @finish="importData"
            @subtable-refresh="importData"
          ></batch-import>
        </block>

        <a-button
          v-permission="['base:user-material-config:save']"
          :disabled="!selectPersonalObj"
          @click="openModals"
        >
          按物料添加
        </a-button>
        <a-button
          v-permission="['base:user-material-config:save']"
          :disabled="!selectPersonalObj"
          @click="handleOpenModal"
        >
          按品类添加
        </a-button>
        <a-button
          v-permission="['base:user-material-config:save']"
          :disabled="!selectPersonalObj"
          @click="handleOpenModa3"
        >
          按供应商添加
        </a-button>
        <a-button
          v-permission="['base:user-material-config:update']"
          :disabled="!selectPersonalObj"
          @click="UpdateClick"
        >
          更新规则
        </a-button>
        <a-button
          v-permission="['base:user-material-config:save']"
          :disabled="!selectPersonalObj || !selectedKeys.length"
          @click="CopyingClick"
        >
          批量复制给指定人
        </a-button>
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button
            v-permission="['base:user-material-config:delete']"
            type="text"
            @click="handleDelete(record)"
            >删除</a-button
          >
        </a-space>
      </template>
    </query-page>
    <myModal
      v-if="showModal"
      :select-personal-obj="selectPersonalObj"
      @close="closeMaterial"
    ></myModal>
    <addModal
      v-if="showModal2"
      :select-personal-obj="selectPersonalObj"
      @close="handleClose"
    ></addModal>
    <supplemodal
      v-if="showModal3"
      :select-personal-obj="selectPersonalObj"
      @close="handleCloseSupplier"
    ></supplemodal>
    <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
      <template #title> 请确认 </template>
      <div>您确定要删除当前所选的数据？</div>
    </a-modal>
    <a-modal v-model:visible="visible1" @ok="handleOk1" @cancel="handleCancel1">
      <template #title> 请确认更新 </template>
      <div><a-progress :percent="0.2" :style="{ width: '90%' }" /></div>
    </a-modal>
    <a-modal
      :visible="visible2"
      @ok="handleOk2"
      @cancel="() => (visible2 = false)"
    >
      <template #title> 请确认更新 </template>
      <personTree @personalClick="personalClick"></personTree>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, defineAsyncComponent } from 'vue';
  // import queryForm from '@/common/components/query-form/index.vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import batchImport from '@/common/components/batch-import/index.vue';
  import {
    formComponentConfig,
    formRenderConfig,
    formRenderKeys,
  } from '@/views/basic-configuration/personnel-matrial/personnelmatrialformlist';
  import {
    tableRenderKeys,
    tableRenderConfig,
    tableComponentConfig,
  } from '@/views/basic-configuration/personnel-matrial/procurementquery-tab';
  import { Message, Modal } from '@arco-design/web-vue';
  import { hasDataAndBack } from '@/common/utils/index';

  import {
    getQueryPage,
    deleteConfig,
    changRule,
    saveByUser,
  } from '@/api/Basimanagementapi/personnel-matrial';
  import useModal from '@/common/hooks/modal';
  import personTree from './components/personTree.vue';
  // 按物料添加
  const myModal = defineAsyncComponent(
    () =>
      import('@/views/basic-configuration/personnel-matrial/persoaddmodal.vue')
  );
  // 按品类添加
  const addModal = defineAsyncComponent(
    () => import('@/views/basic-configuration/personnel-matrial/addmodal.vue')
  );
  // 按供应商添加
  const supplemodal = defineAsyncComponent(
    () =>
      import('@/views/basic-configuration/personnel-matrial/suppliermodal.vue')
  );
  const { showModal, openModal, closeModal } = useModal();
  // import personalTable from './components/personalTable.vue';

  // const size = ref('0.15');
  // const tableRef = ref();
  const selectPersonalObj = ref();
  const selectedKeys = ref([]);
  const isLoading = ref(false);
  const queryForms = ref();
  const renderData = ref();
  const total = ref(0);
  const getData = async (queryInfo: object) => {
    selectedKeys.value = [];
    isLoading.value = true;
    const params = {
      ...queryInfo,
      userId: selectPersonalObj?.value?.id,
    };
    const { data } = await getQueryPage(params);
    renderData.value = data.list;
    total.value = data.total;
    isLoading.value = false;
    // 判断数据为空，但总数不为空
    if (
      hasDataAndBack(
        renderData.value,
        total.value,
        queryForms.value?.getStatus().pageNo
      )
    ) {
      queryForms.value?.setCurrent(queryForms.value.getStatus().pageNo - 1);
      getData(queryForms.value.getStatus());
    }
  };
  const pageChange = () => {
    getData(queryForms.value.getStatus());
  };
  const pageSizeChange = () => {
    getData(queryForms.value.getStatus());
  };
  // 更新规则
  const selectPersonal = ref();
  const personalClick = (val) => {
    if (!visible2.value) {
      selectPersonalObj.value = val;
      getData(queryForms.value.getStatus());
    } else {
      selectPersonal.value = val;
    }
  };
  // 按物料添加
  const openModals = () => {
    openModal();
  };
  // 按品类添加
  const showModal2 = ref(false);
  const handleOpenModal = () => {
    showModal2.value = true;
  };
  // 按供应商添加
  const showModal3 = ref(false);
  const handleOpenModa3 = () => {
    showModal3.value = true;
  };
  const handleClose = () => {
    showModal2.value = false;
    getData(queryForms.value.getStatus());
  };
  const handleCloseSupplier = () => {
    showModal3.value = false;
    getData(queryForms.value.getStatus());
  };
  const closeMaterial = () => {
    closeModal();
    getData(queryForms.value.getStatus());
  };
  const visible = ref(false);
  const visible1 = ref(false);
  const visible2 = ref(false);
  // 删除事件
  const handleDelete = (record) => {
    Modal.warning({
      title: '请确认',
      content: '您确定要删除所选的数据？',
      hideCancel: false,
      onOk: async () => {
        await deleteConfig(record.id || '');
        Message.success('删除成功');
        getData(queryForms.value.getStatus());
        // refresh();
      },
    });
  };
  // 更新规则
  const UpdateClick = () => {
    Modal.warning({
      title: '请确认',
      content: '您确定要更新规则',
      hideCancel: false,
      onOk: async () => {
        const { data } = await changRule({
          userId: selectPersonalObj.value.id,
          userCode: selectPersonalObj.value.userCode,
          userName: selectPersonalObj.value.username,
        });
        if (data) {
          Message.success('更新成功');
          // refresh();
          getData(queryForms.value.getStatus());
        } else {
          Message.warning('更新失败');
        }
      },
    });
    // visible1.value = true;
  };
  const handleOk = () => {
    visible.value = false;
    Message.info({
      content: '删除成功！',
      duration: 5 * 1000,
    });
  };
  const handleCancel = () => {
    visible.value = false;
  };
  const handleOk1 = () => {
    visible.value = false;
    Message.info({
      content: '更新成功',
      duration: 5 * 1000,
    });
  };
  const selectDataList = ref();
  const handleSelectionChange = (itemList: any) => {
    selectDataList.value = itemList.map((item) => {
      return renderData.value.find((i) => i.id === item);
    });
  };
  const handleOk2 = async () => {
    if (!selectPersonalObj.value) {
      Message.warning('请选择人员进行操作');
      return;
    }
    const params = [];
    selectDataList.value.forEach((v) => {
      console.log(v, '000v');
      console.log(selectPersonalObj);
      if (v.addType === '按品类添加') {
        v.addTypes = '1';
      } else if (v.addType === '按供应商添加') {
        v.addTypes = '2';
      } else {
        v.addTypes = '3';
      }
      const obj = {
        secretLevel: v.secretLevel,
        materialId: v.materialId,
        categoryLv1Id: v.categoryLv1Id,
        categoryLv2Id: v.categoryLv2Id,
        categoryLv3Id: v.categoryLv3Id,
        supplierId: v.supplierId,
        addType: v.addTypes,
        materialCode: v.materialCode,
        materialName: v.materialName,
        materialType: v.materialType,
        userId: selectPersonal.value.id,
        userCode: selectPersonal.value.userCode,
        userName: selectPersonal.value.username,
      };
      params.push(obj);
    });
    const { data } = await saveByUser(params);
    if (data) {
      Message.success('操作成功');
      visible2.value = false;
      // selectData.value = [];
      getData(queryForms.value.getStatus());
    }
    console.log(data);
  };
  // 导入数据
  const importData = async () => {
    getData(queryForms.value.getStatus());
  };
  // 批量赋值指定人
  const CopyingClick = () => {
    visible2.value = true;
  };
</script>

<style lang="less" scoped>
  .IconCare {
    width: 10px;
    height: 10px;
    border-bottom: 2px solid #ccc;
  }
  .l {
    border-left: 2px solid #ccc;
    transform: rotateZ(-135deg);
  }
  .r {
    border-right: 2px solid #ccc;
    transform: rotateZ(135deg);
  }
  .layout-demo {
    height: calc(100vh - 200px);
  }
  .layout-demo :deep(.arco-layout-content) {
    color: var(--color-text-2);
    font-weight: 400;
    font-size: 14px;
  }
  .layout-demo :deep(.arco-layout-content) {
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size: 16px;
    font-stretch: condensed;
  }
</style>
